<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class login extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->model('user_model');	
	}
	
	public function index()
	{
		$this->load->view('login/form');
	}
	
	public function logout()
	{
		//Add to Log
		$log = array('user_id'=> $this->session->userdata['user_id'],
					'activity'=> 'logged Out from: '.$this->session->userdata['ip_address'],
					'module'=> 'login',
					'created_on'=> date("Y-m-d H:i:s"));
		
		$this->db->insert('bf_activities', $log);
		
		$this->session->sess_destroy();
		redirect('login');
	}
	
	function auth()
	{
		$this->form_validation->set_rules('username', 'Username/Email', 'trim|required|min_length[3]');
		$this->form_validation->set_rules('password', 'Password', 'trim|required');
		
		if ($this->form_validation->run() == FALSE)
		{
			$data['msg']  = $this->form_validation->getErrorsArray();
			$this->load->view('login/form', $data);
		}
		else
		{
			/*
			 * 1.Set sesstion
			 * 2.redirect to dashboard
			*/
			$user 	= $this->input->post('username');
			$pass 	= $this->input->post('password');
			
			$result = $this->user_model->login($user);
			
			//check password match
			if($result->num_rows == 1)
			{
				$db_result = $result->result_array();
				if($pass == $db_result[0]['password']){
					//set sesstion
						$newdata = array(
					   'username'  => $db_result[0]['username'],
					   'email'     => $db_result[0]['email'],
					   'user_id'    => $db_result[0]['id'],
					   'role'    => $db_result[0]['role_id'],
					   'name'     	=> $db_result[0]['first_name'].' ' .$db_result[0]['last_name'],
					   'logged' => TRUE
				   );

					$this->session->set_userdata($newdata);
					
					//update user last login & last ip
					$data['last_ip'] = $this->session->userdata['ip_address'];
					$data['last_login'] = date("Y-m-d H:i:s");
					
					if($this->user_model->update($this->session->userdata['user_id'],$data)){
						//Add to Log
						$log = array('user_id'=> $this->session->userdata['user_id'],
									'activity'=> 'logged in from: '.$this->session->userdata['ip_address'],
									'module'=> 'login',
									'created_on'=> $data['last_login']);
						
						$this->db->insert('bf_activities', $log);
						
						redirect('/welcome/');
					}
						

				}
				else{
					//username or password not match
					$data['msg']['username'] = "Username or Password not matched!<br>Try again or Contact Grape Admin.";
					$this->load->view('login/form',$data);
				}
			}
			else{
			//username or email not fount in DB
				$data['msg']['username'] = "Username or Password not matched!<br>Try again or Contact Grape Admin.";
				$this->load->view('login/form',$data);
			}
			
		}
	}
	
}
